package com.ruoyi.dynamic.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.CacheKey;
import com.ruoyi.common.redis.cache.CacheTemplate;
import com.ruoyi.dynamic.mapper.RoomMomentMapper;
import com.ruoyi.dynamic.model.constant.DynamicConstant;
import com.ruoyi.dynamic.model.constant.RoomChatRoomKvConstant;
import com.ruoyi.dynamic.model.pojo.entity.*;
import com.ruoyi.dynamic.model.pojo.request.app.AppRoomHeartCreateRequest;
import com.ruoyi.dynamic.model.pojo.request.app.AppRoomHeartGetRequest;
import com.ruoyi.dynamic.model.pojo.request.app.AppRoomSelHeartRequest;
import com.ruoyi.dynamic.model.pojo.request.app.AppRoomSelectMomentRequest;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomGameSelResult;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomHeatResult;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomMaiUserResult;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomMomentSelResult;
import com.ruoyi.dynamic.service.*;
import com.ruoyi.system.api.RemoteAppUserService;
import com.ruoyi.system.api.model.user.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 房间心动交友记录 服务实现类
 * </p>
 *
 * @author Gnc
 * @since 2024-12-27
 */
@Service
public class RoomMomentServiceImpl extends ServiceImpl<RoomMomentMapper, RoomMoment> implements IRoomMomentService {
    @Autowired
    private IRoomService iRoomService;
    @Autowired
    private IMessageService iMessageService;
    @Autowired
    private IRoomMomentRecordService iRoomMomentRecordService;
    @Autowired
    private IRoomTypeService iRoomTypeService;
    @Autowired
    private IRoomMaiRecordService iRoomMaiRecordService;
    @Autowired
    private RemoteAppUserService remoteAppUserService;

    @Override
    public AppRoomHeatResult findStatus(AppRoomHeartGetRequest request, Long userId) {
        if (request.getId().equals(0L)) return AppRoomHeatResult.builder().build();
        RoomMoment verify = verify(request.getId());
        return AppRoomHeatResult.builder()
                .id(verify.getId())
                .status(verify.getStatus())
                .build()
                ;
    }

    @Override
    public RoomMoment verify(Long id) {
        Optional<RoomMoment> roomMoment = lambdaQuery()
                .eq(RoomMoment::getId, id)
                .oneOpt();
        Assert.isTrue(roomMoment.isPresent(), "此游戏记录不存在");
        RoomMoment moment = roomMoment.get();
        Assert.isTrue(!moment.getStatus().equals(DynamicConstant.HeatStatus.END), "此游戏记录已结束");
        return moment;
    }

    @Override
    public Long openGame(AppRoomHeartCreateRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());
        Assert.isTrue(verify.getUserId().equals(userId), "只有主播才能开启游戏");
        RoomType roomType = iRoomTypeService.verify(verify.getRoomTypeId());
        Assert.isTrue(roomType.getId().equals(6L), "此房间不是心动一刻房间无法开启");

        Long count = lambdaQuery()
                .ne(RoomMoment::getStatus, DynamicConstant.HeatStatus.END)
                .eq(RoomMoment::getRoomId, request.getRoomId())
                .count();
        Assert.isTrue(count == 0, "还有未结束的游戏无法开启");

        List<AppRoomMaiUserResult> maiUsers = iRoomService.maiUsers(verify.getId(), DynamicConstant.MaiType.MAI, false, true, 0L, 0);
        Assert.notEmpty(maiUsers, "无嘉宾无法开启");

        Long count1 = iRoomMaiRecordService.lambdaQuery()
                .eq(RoomMaiRecord::getRoomId, verify.getId())
                .eq(RoomMaiRecord::getStatus, DynamicConstant.MaiStatus.Pass)
                .eq(RoomMaiRecord::getStarLocation, DynamicConstant.MomentLocation.Star)
                .count();
        Assert.isTrue(count1 > 0, "无星光嘉宾无法开启");

        List<AppRoomMaiUserResult> appRoomMaiUserResults = maiUsers.stream().filter(res -> res.getMaiNum() == 7).collect(Collectors.toList());
        AppRoomMaiUserResult result = appRoomMaiUserResults.get(0);
        Assert.notNull(result, "无星光嘉宾无法开启");

        String aimKey = CacheKey.ROOM_MAI.getKey(String.valueOf(result.getId()));
        String cacheKey = iRoomService.getRoomCacheKey(aimKey, request.getRoomId(), result.getId());


        RoomMoment moment = new RoomMoment();
        moment.setRoomId(verify.getId());
        moment.setUserId(userId);
        moment.setStatus(DynamicConstant.HeatStatus.JISHAO);
        if (save(moment)) {
            List<RoomMomentRecord> list = maiUsers.stream()
                    .map(res -> {
                        RoomMomentRecord record = new RoomMomentRecord();
                        record.setUserId(res.getId());
                        record.setMaiNum(res.getMaiNum());
                        record.setRoomId(verify.getId());
                        record.setRoomMomentId(moment.getId());
                        record.setUserName(res.getNickName());
                        record.setUserPhoto(res.getPhoto());
                        record.setCreateTime(new Date());
                        record.setLocation(res.getLocation());
                        return record;
                    }).collect(Collectors.toList());

            iRoomMomentRecordService.saveBatch(list);


            AppRoomHeatResult build = AppRoomHeatResult.builder()
                    .status(moment.getStatus())
                    .id(moment.getId())
                    .stepName("自我介绍")
                    .build();

            //发送聊天室属性里面存下当前游戏id以便主持操作
            iMessageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_MOMENT_INFO, JSONObject.toJSONString(build),
                    0, "", "");

            result.setSayStatus(DynamicConstant.SayStatus.Fan);
            CacheTemplate.setCache(cacheKey, result, 1L, TimeUnit.DAYS);

            iMessageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_MOMENT_STAR_SAY,
                    JSONObject.toJSONString(result), 0, "", "");
            return moment.getId();
        }
        return 0L;
    }

    @Override
    public boolean applyStarMai(Long userId, Long id) {
        Room verify = iRoomService.verify(id);
        Assert.isTrue(verify.getRoomTypeId().equals(6), "不是心动一刻房间");

        R<AppUser> userInfo = remoteAppUserService.getUserInfo(userId, SecurityConstants.APP);
        AppUser data = userInfo.getData();

        Long count = iRoomMaiRecordService.lambdaQuery()
                .eq(RoomMaiRecord::getRoomId, id)
                .eq(RoomMaiRecord::getStarLocation, DynamicConstant.MomentLocation.Star)
                .eq(RoomMaiRecord::getStatus, DynamicConstant.CheckStatus.YES)
                .eq(RoomMaiRecord::getMaiNum, 7)
                .count();
        Assert.isTrue(count == 0, "星光嘉宾位已满!");

        iRoomMaiRecordService.add(verify.getId(), verify.getRoomNumber(), userId,
                7, DynamicConstant.MaiType.MAI, DynamicConstant.CheckStatus.NO, data.getPhoto(), data.getNickName(), DynamicConstant.MomentLocation.Star);
        return true;
    }

    @Override
    public void introOver(AppRoomHeartGetRequest request, Long userId) {
        Room room = iRoomService.verify(request.getRoomId());
        Assert.isTrue(room.getUserId().equals(userId), "只有主播能操作");
        RoomMoment verify = verify(request.getId());

        Assert.isTrue(verify.getStatus().equals(DynamicConstant.HeatStatus.JISHAO), "不是自我介绍状态");

        List<AppRoomMaiUserResult> maiUsers = iRoomService.maiUsers(request.getRoomId(), DynamicConstant.MaiType.MAI, false, true, 0L, 0);
        maiUsers = maiUsers.stream().filter(result -> result.getMaiNum().equals(7)).collect(Collectors.toList());
        AppRoomMaiUserResult result = maiUsers.get(0);
        Assert.isTrue(result.getSayStatus().equals(DynamicConstant.SayStatus.Over), "该星光嘉宾发言还未结束");

        verify.setStatus(DynamicConstant.HeatStatus.FAYAN);
        updateById(verify);

        AppRoomHeatResult build = AppRoomHeatResult.builder()
                .id(verify.getId())
                .status(verify.getStatus())
                .stepName("自由发言")
                .build();
        iMessageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_MOMENT_INFO, JSONObject.toJSONString(build), 0, "", "");
    }

    @Override
    public void makeOver(AppRoomHeartGetRequest request, Long userId) {
        Room room = iRoomService.verify(request.getRoomId());
        RoomMoment verify = verify(request.getId());
        Assert.isTrue(verify.getStatus().equals(DynamicConstant.HeatStatus.FAYAN), "不是自由发言状态");
        verify.setStatus(DynamicConstant.HeatStatus.SEL);
        updateById(verify);

        AppRoomHeatResult build = AppRoomHeatResult.builder()
                .id(verify.getId())
                .status(verify.getStatus())
                .stepName("心动选择")
                .build();
        iMessageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_MOMENT_INFO, JSONObject.toJSONString(build), 0, "", "");

    }

    @Override
    public AppRoomMomentSelResult pushResult(AppRoomHeartGetRequest request, Long userId) {
        Room room = iRoomService.verify(request.getRoomId());
        RoomMoment verify = verify(request.getId());
        Assert.isTrue(verify.getStatus().equals(DynamicConstant.HeatStatus.YAN), "不是自由发言状态状态");
        verify.setStatus(DynamicConstant.HeatStatus.GONG);
        updateById(verify);

        List<RoomMomentRecord> records = iRoomMomentRecordService.lambdaQuery()
                .eq(RoomMomentRecord::getRoomId, request.getRoomId())
                .eq(RoomMomentRecord::getRoomMomentId, request.getId())
                .list();

        Set<RoomMomentRecord> uniqueRecords = new HashSet<>();
        for (RoomMomentRecord record : records) {
            boolean isSpa = false;
            for (RoomMomentRecord one : uniqueRecords) {
                if (record.getAimUserId().equals(one.getUserId()) && record.getUserId().equals(one.getAimUserId()) && !record.getAimUserId().equals(0L)) {
                    isSpa = true;
                    record.setAimMaiNum(one.getMaiNum());
                    iRoomMomentRecordService.updateById(record);
                    one.setAimMaiNum(record.getMaiNum());
                    iRoomMomentRecordService.updateById(one);
                    break;
                }
            }
            if (isSpa) {
                uniqueRecords.add(record);
            }
        }
        List<RoomMomentRecord> resultList = new ArrayList<>(uniqueRecords);
        AppRoomHeatResult build = AppRoomHeatResult.builder()
                .id(verify.getId())
                .status(verify.getStatus())
                .stepName("公布结果")
                .momentList(resultList)
                .build();
        iMessageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_MOMENT_INFO, JSONObject.toJSONString(build), 0, "", "");

        return AppRoomMomentSelResult.builder()
                .recordList(resultList)
                .roomId(room.getId())
                .roomMomentId(verify.getId())
                .status(verify.getStatus())
                .build();


    }

    @Override
    public void selOver(AppRoomHeartGetRequest request, Long userId) {
        Room room = iRoomService.verify(request.getRoomId());
        RoomMoment verify = verify(request.getId());
        Assert.isTrue(verify.getStatus().equals(DynamicConstant.HeatStatus.SEL), "不是心动选择状态");
        Long count = iRoomMomentRecordService
                .lambdaQuery()
                .eq(RoomMomentRecord::getRoomMomentId, request.getId())
                .eq(RoomMomentRecord::getIsHeart, 0)
                .count();
        Assert.isTrue(count == 0, "还有玩家未选择");


        verify.setStatus(DynamicConstant.HeatStatus.YAN);
        updateById(verify);

        AppRoomHeatResult build = AppRoomHeatResult.builder()

                .id(verify.getId())
                .status(verify.getStatus())
                .stepName("自由发言")
                .build();
        iMessageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_MOMENT_INFO, JSONObject.toJSONString(build), 0, "", "");

    }

    @Override
    public void isHeart(AppRoomSelHeartRequest request, Long userId) {
        Room room = iRoomService.verify(request.getRoomId());
        RoomMoment verify = verify(request.getId());
        RoomMomentRecord one = iRoomMomentRecordService.lambdaQuery()
                .eq(RoomMomentRecord::getUserId, userId)
                .eq(RoomMomentRecord::getRoomId, request.getRoomId())
                .eq(RoomMomentRecord::getLocation, DynamicConstant.MomentLocation.Heart)
                .eq(RoomMomentRecord::getRoomMomentId, request.getId())
                .one();
        Assert.notNull(one, "您不在此次游戏中无法选择");

        RoomMomentRecord momentRecord = iRoomMomentRecordService.lambdaQuery()
                .eq(RoomMomentRecord::getRoomMomentId, request.getId())
                .eq(RoomMomentRecord::getRoomId, request.getRoomId())
                .eq(RoomMomentRecord::getLocation, DynamicConstant.MomentLocation.Star)
                .one();
        Assert.notNull(momentRecord, "星光嘉宾不存在");
        if (request.getIsHeart().equals(DynamicConstant.IsHeat.YES)) {
            one.setAimUserId(momentRecord.getUserId());
            one.setAimUserPhoto(momentRecord.getUserName());
            one.setAimMaiNum(momentRecord.getMaiNum());
            one.setAimUserName(momentRecord.getUserName());
        }
        one.setIsHeart(request.getIsHeart());
        iRoomMomentRecordService.updateById(one);

        if (request.getIsHeart().equals(DynamicConstant.IsHeat.NO)) {
            AppRoomGameSelResult build = AppRoomGameSelResult.builder()
                    .aimUserId(request.getIsHeart().equals(DynamicConstant.CheckStatus.YES) ? momentRecord.getUserId() : 0L)
                    .aimUserMaiNum(request.getIsHeart().equals(DynamicConstant.CheckStatus.YES) ? momentRecord.getMaiNum() : 0)
                    .userId(userId)
                    .userMaiNum(one.getMaiNum())
                    .build();

            iMessageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_HEAT_SEL, JSONObject.toJSONString(build), 0, "", "");
        }

    }

    @Override
    public void giveUp(AppRoomHeartGetRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());
        RoomMoment moment = verify(request.getId());

        RoomMomentRecord one = iRoomMomentRecordService.lambdaQuery()
                .eq(RoomMomentRecord::getUserId, userId)
                .eq(RoomMomentRecord::getRoomMomentId, request.getId())
                .eq(RoomMomentRecord::getRoomId, request.getRoomId()).one();
        Assert.notNull(one, "您不是星光嘉宾");
        one.setIsHeart(DynamicConstant.IsHeat.NO);
        iRoomMomentRecordService.updateById(one);


    }

    @Override
    public void starSel(AppRoomSelectMomentRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());
        RoomMoment moment = verify(request.getId());

        Long count = iRoomMomentRecordService.lambdaQuery()
                .eq(RoomMomentRecord::getRoomMomentId, request.getId())
                .eq(RoomMomentRecord::getRoomId, request.getRoomId())
                .eq(RoomMomentRecord::getUserId, request.getAimUserId())
                .eq(RoomMomentRecord::getLocation, DynamicConstant.MomentLocation.Heart)
                .count();
        Assert.isTrue(count > 0, "您选择的嘉宾不存在此次游戏中");

        String aimKey = CacheKey.ROOM_MAI.getKey(String.valueOf(request.getAimUserId()));
        String aimCacheKey = iRoomService.getRoomCacheKey(aimKey, request.getRoomId(), request.getAimUserId());
        AppRoomMaiUserResult aimCache = iRoomService.verifyMai(request.getRoomId(), request.getAimUserId(), aimCacheKey);


        RoomMomentRecord one = iRoomMomentRecordService.lambdaQuery()
                .eq(RoomMomentRecord::getUserId, userId)
                .eq(RoomMomentRecord::getRoomMomentId, request.getId())
                .eq(RoomMomentRecord::getRoomId, request.getRoomId()).one();
        Assert.notNull(one, "您不是星光嘉宾");
        one.setAimUserId(request.getAimUserId());
        one.setAimMaiNum(aimCache.getMaiNum());
        one.setAimUserName(aimCache.getNickName());
        one.setAimUserPhoto(aimCache.getPhoto());
        one.setIsHeart(DynamicConstant.IsHeat.YES);
        iRoomMomentRecordService.updateById(one);


        AppRoomGameSelResult build = AppRoomGameSelResult.builder()
                .aimUserId(request.getAimUserId())
                .aimUserMaiNum(aimCache.getMaiNum())
                .userId(userId)
                .userMaiNum(one.getMaiNum())
                .build();

        iMessageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_HEAT_SEL, JSONObject.toJSONString(build), 0, "", "");

    }

    @Override
    public List<RoomMomentRecord> getResult(Long roomId, Long id) {
        List<RoomMomentRecord> records = iRoomMomentRecordService.lambdaQuery()
                .eq(RoomMomentRecord::getRoomId, roomId)
                .eq(RoomMomentRecord::getRoomMomentId, id).list();
        Set<RoomMomentRecord> uniqueRecords = new HashSet<>();
        for (RoomMomentRecord record : records) {
            boolean isSpa = false;
            for (RoomMomentRecord one : uniqueRecords) {
                if (record.getAimUserId().equals(one.getUserId()) && record.getUserId().equals(one.getAimUserId())) {
                    isSpa = true;
                    break;
                }
            }
            if (!isSpa) {
                uniqueRecords.add(record);
            }
        }
        return new ArrayList<>(uniqueRecords);
    }

    @Override
    public List<AppRoomGameSelResult> getMomentResult(AppRoomHeartGetRequest request) {
        List<RoomMomentRecord> list = iRoomMomentRecordService.lambdaQuery()
                .eq(RoomMomentRecord::getRoomMomentId, request.getId())
                .eq(RoomMomentRecord::getRoomId, request.getRoomId())
                .ne(RoomMomentRecord::getAimUserId, 0L)
                .list();

        return list.stream().map(res -> {
            return AppRoomGameSelResult.builder()
                    .aimUserId(res.getAimUserId())
                    .aimUserMaiNum(res.getAimMaiNum())
                    .userMaiNum(res.getMaiNum())
                    .userId(res.getUserId())
                    .build();
        }).collect(Collectors.toList());
    }

    @Override
    public boolean starOverSay(AppRoomHeartGetRequest request, Long userId) {
        Room room = iRoomService.verify(request.getRoomId());
        RoomMoment verify = verify(request.getId());
        Assert.isTrue(verify.getStatus().equals(DynamicConstant.HeatStatus.JISHAO), "该游戏状态不是星光嘉宾自我介绍中");

        String key = CacheKey.ROOM_MAI.getKey(String.valueOf(userId));
        String cacheKey = iRoomService.getRoomCacheKey(key, request.getRoomId(), userId);
        AppRoomMaiUserResult cache = iRoomService.verifyMai(request.getRoomId(), userId, cacheKey);
        Assert.notNull(cache, "您不是星光嘉宾");
        Assert.isTrue(cache.getSayStatus().equals(DynamicConstant.SayStatus.Fan), "您当前不是发言状态");

        Long count = iRoomMomentRecordService.lambdaQuery()
                .eq(RoomMomentRecord::getUserId, userId)
                .eq(RoomMomentRecord::getRoomMomentId, request.getId())
                .eq(RoomMomentRecord::getRoomId, request.getRoomId())
                .eq(RoomMomentRecord::getLocation, DynamicConstant.MomentLocation.Star)
                .count();
        Assert.isTrue(count > 0, "您不是星光嘉宾");
        verify.setStatus(DynamicConstant.HeatStatus.FAYAN);
        if (updateById(verify)) {

            AppRoomHeatResult build = AppRoomHeatResult.builder()
                    .id(verify.getId())
                    .status(verify.getStatus())
                    .stepName("自由发言")
                    .build();
            iMessageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_MOMENT_INFO, JSONObject.toJSONString(build), 0, "", "");

            cache.setSayStatus(DynamicConstant.SayStatus.Over);
            CacheTemplate.setCache(cacheKey, cache, 1L, TimeUnit.DAYS);
            //发送当前结束发言
            iMessageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_MOMENT_STAR_SAY, JSONObject.toJSONString(cache), 0, "", "");
        }
        return true;
    }

    @Override
    public void over(AppRoomHeartGetRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());
        Assert.isTrue(verify.getUserId().equals(userId), "您无权限操作");
        RoomMoment moment = verify(request.getId());
        Assert.isTrue(moment.getStatus().equals(DynamicConstant.HeatStatus.GONG), "目前不是公布结果阶段无法结束");
        moment.setStatus(DynamicConstant.HeatStatus.END);
        updateById(moment);
        AppRoomHeatResult build = AppRoomHeatResult.builder()
                .content(verify.getContent())
                .id(0L)
                .status(verify.getStatus())
                .stepName("游戏结束")
                .build();
        iMessageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_MOMENT_INFO, JSONObject.toJSONString(build), 0, "", "");

        //删除key
        iMessageService.removeRoomKV(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_HEAT_SEL, "", "");
    }


}
